//
//  OANewInViewController.m
//  OASystem
//
//  Created by zhoupengfei on 15/3/28.
//  Copyright (c) 2015年 zpf. All rights reserved.
//

#import "OANewInViewController.h"
#import "HttpTools.h"
#import "MBProgressHUD.h"
#import "GDataDefines.h"
#import "UnDoneModel.h"
#import "OAUnDoneListCell.h"
#import "MJRefresh.h"
#import "Toast+UIView.h"
#import "OAToolBox.h"
#import "PickerChoiceView.h"
#import "TableViewCell.h"

#import "OANewInDetailController.h"
@interface OANewInViewController ()<TFPickerDelegate>
{
    NSInteger selectIndex;
}
@property(nonatomic,strong)NSMutableArray * dataArray;
@property(nonatomic,assign)int totalCounts; //总条数
@property(nonatomic,assign)int currentPage; //当前页
@property (nonatomic,strong)NSMutableArray *mutArray;
@property (nonatomic,strong)NSMutableArray *Array;
@property (nonatomic,strong)NSArray *array;

@property(nonatomic,assign)BOOL isSearching;
@property(nonatomic,copy)NSString * searchText;
@end

@implementation OANewInViewController

//-(void)viewWillAppear:(BOOL)animated{
//    [super viewWillAppear:animated];
//    self.currentPage = 1;
//    [self loadData];
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self requestdata];
        [self setRightItem];
 
    [self.tableView addHeaderWithCallback:^{
        self.currentPage = 1;
if (_isSearching) {
    [self loadSearchMore];

}else{
[self loadData];
 }
    }];
    [self.tableView headerBeginRefreshing];
    
    [self.tableView addFooterWithCallback:^{
        if ((self.currentPage - 1)*KPageSize < self.totalCounts ){
if (_isSearching) {
    [self loadSearchMore];

}else{
[self loadMore];
 }

            
        }else{
            
            [self.tableView footerEndRefreshing];
            [self.view makeToast:@"没有更多了"];
            
        }
        
    }];
    // 分类搜索
    UINib *nib = [UINib nibWithNibName:@"TableViewCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"TableViewCellID"];
        self.mutArray = [NSMutableArray array];
    
 NSArray *arr = @[@{@"title1":@"请点击此处选择类别",@"title2":@"全部"}];
    for (NSDictionary *dict in arr) {
        
        [self.mutArray addObject:dict];
    }
//

_url = exchkind;
_method = @"inDepPage";
_string = @"";
    
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refrshData) name:@"refrshData" object:nil];
}
//搜索内容加载更多
- (void)loadSearchMore
{
 NSString * method = nil;
 //   self.searchText = text;
           method = @"FilesInSearch";
 
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"Condition":_searchText},@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    __weak typeof(self) weakSelf = self;
//    [HttpTools requestWithURL:@"exchSearch" arrays:array method:method success:^(id JSON) {
    [HttpTools postWithURL:exchSearch arrays:array method:method success:^(id JSON) {

        if (self.currentPage == 1) {
            [self.dataArray removeAllObjects];
        }
    [self.dataArray addObjectsFromArray:[self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]]];
        [weakSelf.tableView footerEndRefreshing];
        [weakSelf.tableView reloadData];
        weakSelf.currentPage++;
        
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
        
    } failure:^(NSError *error) {
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
    }];
    
    
}



-(void)setRightItem{
            UIBarButtonItem * rightIem = [[UIBarButtonItem alloc] initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(searchAction)];
        self.navigationItem.rightBarButtonItem = rightIem;
   
    
}
#pragma mark 搜素
-(void)searchAction{
    
    [UIAlertView showWithTitle:@"搜索" message:nil style:UIAlertViewStylePlainTextInput cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
        [self.view endEditing:YES];
        
        if (buttonIndex == 1) {
            UITextField * textField = [alertView textFieldAtIndex:0];
            if (textField.text.length !=0) {
                
                [self.dataArray removeAllObjects];
                self.isSearching = YES;
                self.currentPage = 1;
                [self loadSearchData:textField.text];
            }
            
        }
        
    }];
    
}
-(void)loadSearchData:(NSString*)text{
    NSString * method = nil;
    self.searchText = text;
            method = @"FilesInSearch";
    
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"Condition":text},@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    __weak typeof(self) weakSelf = self;
   [HttpTools postWithURL:exchSearch arrays:array method:method success:^(id JSON) {
        if (self.currentPage == 1) {
            [self.dataArray removeAllObjects];
        }
        [self.dataArray addObjectsFromArray:[self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]]];

        [weakSelf.tableView footerEndRefreshing];
        [weakSelf.tableView reloadData];
        weakSelf.currentPage++;
        
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
        
    } failure:^(NSError *error) {
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
    }];
    
    
}

- (void)requestdata{
NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId}];
    [HttpTools requestWithURL:@"exchkind" arrays:array method:@"getInDep" success:^(id JSON) {
     NSArray *array = JSON [@"data"];
     _Array = [NSMutableArray array];
      [_Array addObject:@"全部"];
for (NSDictionary *dic in array) {
    NSString *str = dic[@"gwFstword"];
    [_Array addObject:str];
    
}
  _array = _Array;
        [self.tableView reloadData];
                    } failure:^(NSError *error) {
        [self.tableView headerEndRefreshing];
        
    }];

}


-(void)refrshData{
    self.currentPage = 1;
    [self loadData]; //加载网络数据
}


-(NSMutableArray*)dataArray{
    if (_dataArray == nil) {
        _dataArray =   [NSMutableArray array];
    }
    return _dataArray;
}

#pragma mark 加载网络数据
-(void)loadData{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"viw":_string},@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%d",1]}];
    [HttpTools postWithURL:_url arrays:array method:_method success:^(id JSON) {
        if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
        self.dataArray =  [self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]];
        [self.tableView reloadData];
        [self.tableView headerEndRefreshing];
        self.currentPage++;
        if (self.dataArray.count ==0) {
            [self.view makeToast:@"暂时还没最新收文哦"];
        }
    } failure:^(NSError *error) {
        [self.tableView headerEndRefreshing];
        
    }];
    
}

#pragma mark 加载更多
-(void)loadMore{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"viw":_string},@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools postWithURL:_url arrays:array method:_method success:^(id JSON) {
        [self.dataArray addObjectsFromArray:[self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]]];
        self.currentPage++;
                [self.tableView reloadData];

        [self.tableView footerEndRefreshing];
    } failure:^(NSError *error) {
        [self.tableView footerEndRefreshing];
    }];
    
}


//得到服务器返回数据中的标题
//传参数：一个服务器返回的二进制数据
-(NSMutableArray*)getDataList:(NSData*)data
{

if (_isSearching) {
NSMutableArray * array = [NSMutableArray array];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（<交换 >）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（数据）
    NSArray *dataArray= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement * elemtenData in dataArray) {
        NSArray * subElement = [elemtenData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in subElement) {
            UnDoneModel * model = [[UnDoneModel alloc] init];
            GDataXMLElement * titleElement = [[data elementsForName:@"标题"] objectAtIndex:0];
            
            
              GDataXMLElement * timeElement = [[data elementsForName:@"接收时间"] objectAtIndex:0];
 
                       GDataXMLElement * fileIdElement = [[data elementsForName:@"标识"] objectAtIndex:0];
            model.title = [titleElement stringValue];
            model.time = [timeElement stringValue];
            model.fileId = [fileIdElement stringValue];
            [array addObject:model];
        }
    }
    
    NSArray *countArray= [rootElement elementsForName:@"控制"];
    for (GDataXMLElement * data in countArray) {
        GDataXMLElement * countElement = [[data elementsForName:@"条数"] objectAtIndex:0];
        NSString * counts = [countElement stringValue];
        self.totalCounts = [counts intValue] ;
        
    }
    self.title = [NSString stringWithFormat:@"最新收文(%d)",self.totalCounts];
    return array;

}else{
NSMutableArray * array = [NSMutableArray array];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（<交换 >）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（数据）
    NSArray *dataArray= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement * elemtenData in dataArray) {
        NSArray * subElement = [elemtenData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in subElement) {
            UnDoneModel * model = [[UnDoneModel alloc] init];
            GDataXMLElement * titleElement = [[data elementsForName:@"标题"] objectAtIndex:0];
            
            
              GDataXMLElement * timeElement = [[data elementsForName:@"时间"] objectAtIndex:0];
 
                       GDataXMLElement * fileIdElement = [[data elementsForName:@"标识"] objectAtIndex:0];
            model.title = [titleElement stringValue];
            model.time = [timeElement stringValue];
            model.fileId = [fileIdElement stringValue];
            [array addObject:model];
        }
    }
    
    NSArray *countArray= [rootElement elementsForName:@"控制"];
    for (GDataXMLElement * data in countArray) {
        GDataXMLElement * countElement = [[data elementsForName:@"条数"] objectAtIndex:0];
        NSString * counts = [countElement stringValue];
        self.totalCounts = [counts intValue] ;
        
    }
    self.title = [NSString stringWithFormat:@"最新收文(%d)",self.totalCounts];
    return array;
 }

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
if(indexPath.row==0)
{
return 40;
}
else{
    UnDoneModel * model = self.dataArray[indexPath.row-1];
    CGFloat height = 0;
    CGFloat  titlesize  = [OAToolBox sizebyText:model.title font:14 minsWidth:60];
    
    NSString * desstring = [NSString stringWithFormat:@"%@",model.time];
    CGFloat dessize = [OAToolBox sizebyText:desstring font:13 minsWidth:60];;
    height = titlesize + dessize + 20;
    return  height;
}
}



#pragma mark UITableView dataScource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

if (indexPath.row==0) {
    NSDictionary *dict = [self.mutArray objectAtIndex:0];
    
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TableViewCellID"];
    cell.leftLb.text = dict[@"title1"];
    cell.rightLb.text = dict[@"title2"];
   return cell;
}
 else{

    OAUnDoneListCell * cell = [OAUnDoneListCell cellWithTableView:tableView];
    UnDoneModel * model = self.dataArray[indexPath.row-1];
    cell.model = model;
    return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

if (indexPath.row == 0){
PickerChoiceView *picker = [[PickerChoiceView alloc]initWithFrame:self.view.bounds];
    selectIndex = indexPath.row;
    picker.delegate = self;
    if (indexPath.section == 0) {
        
        picker.selectLb.text = @"部门选择";
        picker.customArr = _array;
    }

    [self.view addSubview:picker];

}else{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
      UnDoneModel * model = self.dataArray[indexPath.row-1];
    detailViewController * detailVC = (detailViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"detail"];
detailVC.fileId = model.fileId;
detailVC.type = @"contentIn";

[self.navigationController pushViewController:detailVC animated:YES];
}
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count+1;
}
- (void)PickerSelectorIndixString:(NSString *)str{

    NSDictionary *dict = [self.mutArray objectAtIndex:0];
    
    NSMutableDictionary *muDict = [NSMutableDictionary dictionaryWithDictionary:dict];
    [muDict setObject:str forKey:@"title2"];
    [muDict setObject:@"" forKey:@"title1"];
    [self.mutArray replaceObjectAtIndex:0 withObject:muDict];
//    [self.mutArray removeObjectAtIndex:selectIndex];
//    [self.mutArray insertObject:muDict atIndex:selectIndex];

if ([str isEqualToString:@"全部"]) {
    _string = @"";
}else{

_string = str;
}
_currentPage = 1;
    [self loadData];
    NSLog(@"%@",str);
    [self.tableView reloadData];
    
}



@end
